package org.example.boot.usercenter.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.boot.usercenter.common.ErrorCode;
import org.example.boot.usercenter.exception.BusinessException;
import org.example.boot.usercenter.model.entity.Product;
import org.example.boot.usercenter.model.request.PageRequest;
import org.example.boot.usercenter.model.vo.ProductViewVo;
import org.example.boot.usercenter.service.ProductService;
import org.example.boot.usercenter.mapper.ProductMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
* @author HEZHAOGUI
* @description 针对表【product(商品表)】的数据库操作Service实现
* @createDate 2025-03-18 21:19:30
*/
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
    implements ProductService{

    @Override
    public List<ProductViewVo> getListProducts(PageRequest pageRequest) {
        if (pageRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (pageRequest.getPageSize() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(pageRequest.getPageNum() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 构建翻页对象
        IPage<Product> productPage = new Page<>(pageRequest.getPageNum(),pageRequest.getPageSize());
        // 调用page方法
        IPage<Product> page = page(productPage);
        // 获取当前页的数据列表
        List<Product> records = page.getRecords();
        // 转化为迭代器进行vo处理
        Iterator<Product> productIterator = records.iterator();
        // 创建返回的Vo对象数组
        List<ProductViewVo> outcomeVo = new ArrayList<>();
        // 遍历迭代器传递对象转化
        while (productIterator.hasNext()){
            ProductViewVo productVo = new ProductViewVo();
            Product product = productIterator.next();
            BeanUtils.copyProperties(product,productVo);
            outcomeVo.add(productVo);
        }
        return outcomeVo;
    }
}




